package com.example.admin.brainwave.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.example.admin.brainwave.R;
import com.example.admin.brainwave.base.BaseActivity;
import com.example.admin.brainwave.bean.CurrencyBean;
import com.example.admin.brainwave.bean.DictionaryBean;
import com.example.admin.brainwave.bean.GetTesteeInfoBean;
import com.example.admin.brainwave.bean.ListValuesBean;
import com.example.admin.brainwave.net.GetImageTask;
import com.example.admin.brainwave.net.GetListValuesTask;
import com.example.admin.brainwave.net.GetTesteeInfoTask;
import com.example.admin.brainwave.net.SaveTesteeInfoTask;
import com.example.admin.brainwave.net.UpLoadAvatarTask;
import com.example.admin.brainwave.ui.adapter.DictionaryAdapter;
import com.example.admin.brainwave.utils.BitmapUtil;
import com.example.admin.brainwave.utils.Const;
import com.example.admin.brainwave.utils.RecycleViewDivider;
import com.example.admin.brainwave.utils.RxFileTool;
import com.example.admin.brainwave.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PersonalDataActivity extends BaseActivity {

    @BindView(R.id.iv_top_back)
    ImageView ivTopBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_top_right)
    TextView tvTopRight;
    @BindView(R.id.iv_personal_head)
    CircleImageView ivPersonalHead;
    @BindView(R.id.et_personal_name)
    EditText etPersonalName;
    @BindView(R.id.tv_personal_sex)
    TextView tvPersonalSex;
    @BindView(R.id.et_personal_age)
    EditText etPersonalAge;
    @BindView(R.id.tv_personal_nation)
    TextView tvPersonalNation;
    @BindView(R.id.tv_personal_education)
    TextView tvPersonalEducation;
    @BindView(R.id.et_personal_profession)
    EditText etPersonalProfession;
    @BindView(R.id.et_personal_diseasehistory)
    EditText etPersonalDiseasehistory;

    private String nationCode;
    private String educationCode;
    private String sexCode;
    private final int REQUEST_CODE = 99;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_personal_data;
    }

    @Override
    protected void initView() {
        tvTopTitle.setText(getResources().getText(R.string.personal_data));
        tvTopRight.setVisibility(View.VISIBLE);
        tvTopRight.setText(getResources().getString(R.string.save));
    }

    @Override
    protected void initData() {
        new GetTesteeInfoTask(this, o -> {
            if (o != null) {
                GetTesteeInfoBean info = (GetTesteeInfoBean) o;
                if (Const.OKCODE.equals(info.getCode())) {
                    showInfo(info);
                    getlistValues("nation", 0, info.getResult());
                    getlistValues("education", 0, info.getResult());
                } else {
                    ToastUtil.showShort(PersonalDataActivity.this, info.getMessage());
                }
            }
        }).execute();
        new GetImageTask(this, o -> {
            if (o != null) {
                BitmapUtil.loadBitmap((String) o, PersonalDataActivity.this, ivPersonalHead);
            }
        }).execute();
    }

    private void showInfo(GetTesteeInfoBean info) {
        etPersonalName.setText(info.getResult().getFullName());
        if (!TextUtils.isEmpty(info.getResult().getGender())) {
            sexCode = info.getResult().getGender();
            if ("M".equals(info.getResult().getGender())) {
                tvPersonalSex.setText(getResources().getString(R.string.male));
            } else {
                tvPersonalSex.setText(getResources().getString(R.string.famale));
            }
        }
        etPersonalAge.setText(info.getResult().getAge());
        etPersonalProfession.setText(info.getResult().getProfession());
        etPersonalDiseasehistory.setText(info.getResult().getDiseaseHistory());
    }

    @Override
    protected void addListener() {
        ivTopBack.setOnClickListener(v -> finish());
        tvTopRight.setOnClickListener(v -> saveMsg());
        tvPersonalNation.setOnClickListener(v -> getlistValues("nation", 1, null));
        tvPersonalEducation.setOnClickListener(v -> getlistValues("education", 1, null));
        tvPersonalSex.setOnClickListener(v -> showSexDialog());
        ivPersonalHead.setOnClickListener(v -> {
            ImageSelector.builder()
                    .useCamera(true) // 设置是否使用拍照
                    .setSingle(true)  //设置是否单选
                    .setViewImage(true) //是否点击放大图片查看,，默认为true
                    .start(this, REQUEST_CODE); // 打开相册
        });
    }

    private void getlistValues(String type, int isInit, GetTesteeInfoBean.ResultBean bean) {
        new GetListValuesTask(this, o -> {
            if (o != null) {
                ListValuesBean listValuesBean = (ListValuesBean) o;
                if (Const.OKCODE.equals(listValuesBean.getCode()) && listValuesBean.getResult() != null) {
                    if (isInit == 1) {
                        showDialog(listValuesBean.getResult(), type);
                    } else if (isInit == 0) {
                        if (type.equals("nation")) {
                            for (int i = 0; i < listValuesBean.getResult().size(); i++) {
                                if (listValuesBean.getResult().get(i).getCode().equals(bean.getNationCode())) {
                                    tvPersonalNation.setText(listValuesBean.getResult().get(i).getDescription());
                                    nationCode = listValuesBean.getResult().get(i).getCode();
                                    break;
                                }
                            }
                        } else if (type.equals("education")) {
                            for (int i = 0; i < listValuesBean.getResult().size(); i++) {
                                if (listValuesBean.getResult().get(i).getCode().equals(bean.getEducationCode())) {
                                    tvPersonalEducation.setText(listValuesBean.getResult().get(i).getDescription());
                                    educationCode = listValuesBean.getResult().get(i).getCode();
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    ToastUtil.showShort(PersonalDataActivity.this, listValuesBean.getMessage());
                }
            }
        }).execute(type);
    }


    private void showDialog(List<ListValuesBean.ResultBean> list, String type) {
        if (list != null && list.size() > 0) {
            List<DictionaryBean> data = new ArrayList<>();
            int pos = -1;
            for (int i = 0; i < list.size(); i++) {
                data.add(new DictionaryBean(list.get(i).getDescription()));
                if (type.equals("nation")) {
                    if (!TextUtils.isEmpty(nationCode)) {
                        if (list.get(i).getCode().equals(nationCode)) {
                            pos = i;
                        }
                    }
                } else if (type.equals("education")) {
                    if (!TextUtils.isEmpty(educationCode)) {
                        if (list.get(i).getCode().equals(educationCode)) {
                            pos = i;
                        }
                    }
                }
            }

            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.please_choose)
                    .adapter(new DictionaryAdapter(R.layout.item_dictionary, data), new LinearLayoutManager(this))
                    .positiveText(R.string.done)
                    .show();
            dialog.getRecyclerView().addItemDecoration(new RecycleViewDivider(
                    this, LinearLayoutManager.VERTICAL, 1, Color.parseColor("#e5e5e5")));
            DictionaryAdapter dadapter = (DictionaryAdapter) dialog.getRecyclerView().getAdapter();
            if (pos != -1) {
                dadapter.setChoose(pos);
            }
            dadapter.setOnItemClickListener((adapter, view, position) -> {
                if (type.equals("nation")) {
                    dadapter.setChoose(position);
                    nationCode = list.get(position).getCode();
                    tvPersonalNation.setText(list.get(position).getDescription());
                } else if (type.equals("education")) {
                    dadapter.setChoose(position);
                    educationCode = list.get(position).getCode();
                    tvPersonalEducation.setText(list.get(position).getDescription());
                }
            });
        }
    }

    private void showSexDialog() {
        List<DictionaryBean> data = new ArrayList<>();
        data.add(new DictionaryBean(getResources().getString(R.string.male)));
        data.add(new DictionaryBean(getResources().getString(R.string.famale)));
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.please_choose)
                .adapter(new DictionaryAdapter(R.layout.item_dictionary, data), new LinearLayoutManager(this))
                .positiveText(R.string.done)
                .show();
        dialog.getRecyclerView().addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 1, Color.parseColor("#e5e5e5")));
        int pos = -1;
        if (!TextUtils.isEmpty(sexCode)) {
            if ("M".equals(sexCode)) {
                pos = 0;
            } else if ("F".equals(sexCode)) {
                pos = 1;
            }
        }
        DictionaryAdapter adapter = (DictionaryAdapter) dialog.getRecyclerView().getAdapter();
        if (pos != -1) {
            adapter.setChoose(pos);
        }
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (position == 0) {
                adapter.setChoose(position);
                sexCode = "M";
                tvPersonalSex.setText(getResources().getString(R.string.male));
            } else if (position == 1) {
                adapter.setChoose(position);
                sexCode = "F";
                tvPersonalSex.setText(getResources().getString(R.string.famale));
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> images = data.getStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT);
                Glide.with(this)
                        .load(new File(images.get(0)))
                        .into(ivPersonalHead);
                saveImage(images.get(0));
            } else {
                Toast.makeText(this, getResources().getString(R.string.no_data), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void saveImage(String path) {
        List<String> photos = new ArrayList<>();
        photos.add(path);
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(RxFileTool.getRootPath().getAbsolutePath())
                .filter(path1 -> !(TextUtils.isEmpty(path1) || path1.toLowerCase().endsWith(".gif")))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        new UpLoadAvatarTask(PersonalDataActivity.this, o -> {
                            if (o != null) {
                                CurrencyBean bean = (CurrencyBean) o;
                                ToastUtil.showShort(PersonalDataActivity.this, bean.getMessage());
                                setResult(RESULT_OK);
                            }
                        }).execute(file.getAbsolutePath());
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();

    }

    private void saveMsg() {
        if (isEmpty()) {
            String name = etPersonalName.getText().toString();
            String age = etPersonalAge.getText().toString();
            String profession = etPersonalProfession.getText().toString();
            String diseasehistory = etPersonalDiseasehistory.getText().toString();
            new SaveTesteeInfoTask(this, o -> {
                if (o != null) {
                    CurrencyBean bean = (CurrencyBean) o;
                    if (Const.OKCODE.equals(bean.getCode())) {
                        ToastUtil.showShort(PersonalDataActivity.this, bean.getMessage());
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        ToastUtil.showShort(PersonalDataActivity.this, bean.getMessage());
                    }
                }
            }).execute(name, sexCode, age, nationCode, educationCode, profession, diseasehistory);
        }
    }


    private boolean isEmpty() {
        if (TextUtils.isEmpty(etPersonalName.getText().toString())) {
            ToastUtil.showShort(this, getResources().getString(R.string.name) + " " + getResources().getString(R.string.not_null));
            return false;
        }
        if (TextUtils.isEmpty(sexCode)) {
            ToastUtil.showShort(this, getResources().getString(R.string.sex) + " " + getResources().getString(R.string.not_null));
            return false;
        }
        if (TextUtils.isEmpty(etPersonalAge.getText().toString())) {
            ToastUtil.showShort(this, getResources().getString(R.string.age) + " " + getResources().getString(R.string.not_null));
            return false;
        }
        if (TextUtils.isEmpty(nationCode)) {
            ToastUtil.showShort(this, getResources().getString(R.string.nation) + " " + getResources().getString(R.string.not_null));
            return false;
        }
        if (TextUtils.isEmpty(educationCode)) {
            ToastUtil.showShort(this, getResources().getString(R.string.educational_level) + " " + getResources().getString(R.string.not_null));
            return false;
        }
        if (TextUtils.isEmpty(etPersonalProfession.getText().toString())) {
            ToastUtil.showShort(this, getResources().getString(R.string.occupation) + " " + getResources().getString(R.string.not_null));
            return false;
        }
        if (TextUtils.isEmpty(etPersonalDiseasehistory.getText().toString())) {
            ToastUtil.showShort(this, getResources().getString(R.string.history_of_disease) + " " + getResources().getString(R.string.not_null));
            return false;
        }
        return true;
    }

}
